package com.imut.hcdp.job;

import com.imut.hcdp.domain.HcdpTrainRoute;
import com.imut.hcdp.mapper.HcdpTrainRouteMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 行程任务
 */
@Component
@Slf4j
public class RouteJob {

    @Autowired
    private HcdpTrainRouteMapper hcdpTrainRouteMapper;

    /**
     * 到点发车
     */
    @Scheduled(cron = "0 0/2 * * * ?")
    public void waitRoute(){
        log.info("waitRoute 任务轮询开始");
        List<HcdpTrainRoute> hcdpTrainRoutes =
                hcdpTrainRouteMapper.selectHcdpTrainRouteList(new HcdpTrainRoute().setStatus(1L));
        if(CollectionUtils.isEmpty(hcdpTrainRoutes)){
            return;
        }
        for (int i = 0; i < hcdpTrainRoutes.size(); i++) {
            HcdpTrainRoute hcdpTrainRoute = hcdpTrainRoutes.get(i);
            Long sTime = hcdpTrainRoute.getSTime().getTime();
            if(System.currentTimeMillis() >= sTime){
                hcdpTrainRouteMapper.updateHcdpTrainRoute(new HcdpTrainRoute().setId(hcdpTrainRoute.getId()).setStatus(2L));
                log.info("车次：{},{}-{} 已发车！",hcdpTrainRoute.getTraincode(),hcdpTrainRoute.getSCity(),hcdpTrainRoute.getECity());
            }
        }
    }

    /**
     * 行程结束
     */
    @Scheduled(cron = "0 0/2 * * * ?")
    public void finalRoute(){
        log.info("finalRoute 任务轮询开始");
        List<HcdpTrainRoute> hcdpTrainRoutes =
                hcdpTrainRouteMapper.selectHcdpTrainRouteList(new HcdpTrainRoute().setStatus(2L));
        if(CollectionUtils.isEmpty(hcdpTrainRoutes)){
            return;
        }
        for (int i = 0; i < hcdpTrainRoutes.size(); i++) {
            HcdpTrainRoute hcdpTrainRoute = hcdpTrainRoutes.get(i);
            Long eTime = hcdpTrainRoute.getETime().getTime();
            if(System.currentTimeMillis() >= eTime){
                hcdpTrainRouteMapper.updateHcdpTrainRoute(new HcdpTrainRoute().setId(hcdpTrainRoute.getId()).setStatus(3L));
                log.info("车次：{},{}-{} 行程结束！",hcdpTrainRoute.getTraincode(),hcdpTrainRoute.getSCity(),hcdpTrainRoute.getECity());
            }
        }
    }
}
